package com.ningmengs789.live.ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ningmengs789.live.R;
import com.ningmengs789.live.http.JsonBuilder;
import com.ningmengs789.live.http.OKHttpUtils;
import com.ningmengs789.live.Interface.RequestCallback;
import com.ningmengs789.live.live.live.common.utils.DialogUitl;
import com.ningmengs789.live.oss.CosXmlUtils;
import com.ningmengs789.live.net.response.OssImageResponse;
import com.ningmengs789.live.net.response.OssVideoResponse;
import com.ningmengs789.live.net.utils.NToast;
import com.ningmengs789.live.ui.widget.RoundFrameLayout;
import com.ningmengs789.live.ui.widget.dialogorPopwindow.UploadDialog;
import com.ningmengs789.live.utils.CommonUtils;
import com.ningmengs789.live.utils.UserInfoUtil;
import com.bumptech.glide.Glide;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.common.ImageLoader;
import com.yuyh.library.imgsel.config.ISListConfig;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class DaRenRenZhengActivity extends BaseActivity implements View.OnClickListener, CosXmlUtils.OSSResultListener{

    public static final int REQUEST_CODE_SELECT = 1005;

    @BindView(R.id.tv_title_center)
    TextView tv_title_center;

    @BindView(R.id.realName)
    EditText realName;
    @BindView(R.id.cardNumber)
    EditText cardNumber;

    @BindView(R.id.card1Layout)
    RoundFrameLayout card1Layout;
    @BindView(R.id.mengban1)
    ImageView mengban1;

    @BindView(R.id.card2Layout)
    RoundFrameLayout card2Layout;
    @BindView(R.id.mengban2)
    ImageView mengban2;

    @BindView(R.id.card3Layout)
    RoundFrameLayout card3Layout;
    @BindView(R.id.mengban3)
    ImageView mengban3;

    @BindView(R.id.submit)
    Button submit;

    private int flag;

    private String path1;
    private String path2;
    private String path3;

    private CosXmlUtils uploadOssUtils;

    private String userId;
    private int daren_status;

    private ArrayList<String> paths = new ArrayList<>();
    private UploadDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_daren_renzheng);
        ButterKnife.bind(this);
        setHeadLayout();

        initView();
        initEvent();
    }

    private void initView() {
        tv_title_center.setVisibility(View.VISIBLE);
        tv_title_center.setText(R.string.daren_title);

        userId = UserInfoUtil.getMiTencentId();
        daren_status = UserInfoUtil.getDarenStatus();

        // 自定义图片加载器
        ISNav.getInstance().init(new ImageLoader() {
            @Override
            public void displayImage(Context context, String path, ImageView imageView) {
                Glide.with(context).load(path).into(imageView);
            }
        });
    }

    private void initEvent() {
        submit.setOnClickListener(this);

        card1Layout.setOnClickListener(this);
        card2Layout.setOnClickListener(this);
        card3Layout.setOnClickListener(this);

        uploadOssUtils = new CosXmlUtils(this);
        uploadOssUtils.setOssResultListener(this);

        if (daren_status == 0) {
        } else if (daren_status == 1) {
            realName.setEnabled(false);
            cardNumber.setEnabled(false);
            card1Layout.setClickable(false);
            card2Layout.setClickable(false);
            card3Layout.setClickable(false);
            submit.setVisibility(View.GONE);

            DialogUitl.showSimpleHintDialog(mContext, getString(R.string.prompt), getString(R.string.confirm), getString(R.string.cancel),
                    getString(R.string.dialog_title), true, true,
                    new DialogUitl.SimpleCallback2() {
                        @Override
                        public void onCancelClick() {
                            finish();
                        }
                        @Override
                        public void onConfirmClick(Dialog dialog, String content) {
                            dialog.dismiss();
                        }
                    });

            getDarenAuth();
        } else if (daren_status == 2) {
            realName.setEnabled(false);
            cardNumber.setEnabled(false);
            card1Layout.setClickable(false);
            card2Layout.setClickable(false);
            card3Layout.setClickable(false);
            submit.setVisibility(View.GONE);

            NToast.shortToast(this,"主播认证审核通过");

            getDarenAuth();
        } else if (daren_status == 10) {
            DialogUitl.showSimpleHintDialog(mContext, getString(R.string.prompt), getString(R.string.dialog_title1),
                    true, new DialogUitl.SimpleCallback() {
                        @Override
                        public void onConfirmClick(Dialog dialog, String content) {
                            dialog.dismiss();
                        }
                    });
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.submit:
                if (TextUtils.isEmpty(realName.getText().toString().trim())){
                    NToast.shortToast(this,"请输入姓名");
                    return;
                }
                if (TextUtils.isEmpty(cardNumber.getText().toString().trim())){
                    NToast.shortToast(this,"请输入身份证号");
                    return;
                }

                paths.clear();
                if (TextUtils.isEmpty(path1)
                        || TextUtils.isEmpty(path2)
                        ||TextUtils.isEmpty(path3)) {
                    Toast.makeText(this, R.string.daren_message, Toast.LENGTH_SHORT).show();
                    return;
                }
                paths.add(path1);
                paths.add(path2);
                paths.add(path3);

                dialog = new UploadDialog(this);
                dialog.show(300);
                dialog.uploadPhoto(paths.size());

                ossUploadList();
                break;
            case R.id.card1Layout:
                flag = 1;
                tickPhoto();
                break;
            case R.id.card2Layout:
                flag = 2;
                tickPhoto();
                break;
            case R.id.card3Layout:
                flag = 3;
                tickPhoto();
                break;
        }
    }

    private void tickPhoto() {
        // 自由配置选项
        ISListConfig config = new ISListConfig.Builder()
                // 是否多选, 默认true
                .multiSelect(false)
                // 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
                .rememberSelected(false)
                // “确定”按钮背景色
                .btnBgColor(Color.TRANSPARENT)
                // “确定”按钮文字颜色
                .btnTextColor(Color.WHITE)
                // 使用沉浸式状态栏
                .statusBarColor(Color.parseColor("#ffd100"))
                // 返回图标ResId
                .backResId(R.drawable.head_back)
                // 标题
                .title(getString(R.string.per_1))
                // 标题文字颜色
                .titleColor(Color.WHITE)
                // TitleBar背景色
                .titleBgColor(Color.parseColor("#ffd100"))
                // 裁剪大小。needCrop为true的时候配置
                .cropSize(1, 1, 400, 400)
                .needCrop(true)
                // 第一个是否显示相机，默认true
                .needCamera(true)
                // 最大选择图片数量，默认9
                .maxNum(9)
                .build();

        // 跳转到图片选择器
        ISNav.getInstance().toListActivity(this, config, REQUEST_CODE_SELECT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_SELECT:
                //添加图片返回
                if (data != null) {
                    List<String> pathList = data.getStringArrayListExtra("result");
                    if (flag == 1){
                        path1 = pathList.get(0);
                        Glide.with(mContext).load(path1).into(mengban1);
                    }else if (flag == 2){
                        path2 = pathList.get(0);
                        Glide.with(mContext).load(path2).into(mengban2);
                    }else if (flag == 3){
                        path3 = pathList.get(0);
                        Glide.with(mContext).load(path3).into(mengban3);
                    }
                }
                break;
        }
    }

    //主播认证
    private void verifyDaren(ArrayList<OssImageResponse> responses){
        if (responses == null || responses.size() == 0){
            NToast.shortToast(mContext, "上传失败，请重试");
            return;
        }
        String body = "";
        try {
            body = new JsonBuilder()
                    .put("real_name", realName.getText().toString())//真实姓名
                    .put("idcard_no", cardNumber.getText().toString())//身份证号
                    .put("idcard_front", responses.get(0).getObject())//身份证正面
                    .put("idcard_back", responses.get(1).getObject())//身份证反面
                    .put("life_photo", responses.get(2).getObject())//日常生活照
                    .build();
        } catch (JSONException e) {
        }
        OKHttpUtils.getInstance().getRequest(/*"app/user/verifyDaren"*/"app/verify/verifyDaren", body, new RequestCallback() {
            @Override
            public void onError(int errCode, String errInfo) {
                NToast.shortToast(mContext, errInfo);
                finish();
            }
            @Override
            public void onSuccess(String result) {
                DialogUitl.showSimpleHintDialog(mContext,
                        getString(R.string.prompt),
                        getString(R.string.dialog_title),
                        true, new DialogUitl.SimpleCallback() {
                            @Override
                            public void onConfirmClick(Dialog dialog, String content) {
                                dialog.dismiss();
                                finish();
                            }
                        });
            }
        });
    }

    private void getDarenAuth(){
        OKHttpUtils.getInstance().getRequest("app/verify/getDarenAuth"/*"app/user/getDarenAuth"*/, "", new RequestCallback() {
            @Override
            public void onError(int errCode, String errInfo) {
            }
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject data = new JSONObject(result);
                    String idcard_front = data.getString("idcard_front");
                    String idcard_back = data.getString("idcard_back");
                    String idcard_no = data.getString("idcard_no");
                    String real_name = data.getString("real_name");
                    String life_photo = data.getString("life_photo");

                    realName.setText(real_name);
                    cardNumber.setText(idcard_no);
                    Glide.with(mContext).load(CommonUtils.getUrl(idcard_front)).into(mengban1);
                    Glide.with(mContext).load(CommonUtils.getUrl(idcard_back)).into(mengban2);
                    Glide.with(mContext).load(CommonUtils.getUrl(life_photo)).into(mengban3);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void ossUploadList() {
        //（1:个人相册 2:个人视频 3:个人语音介绍 4:达人认证 5:实名认证 6:个人头像 11:动态图片 12:动态视频 21:直播间封面）
        uploadOssUtils.ossUploadList(paths, "image", /*4*/5, userId, dialog);
    }

    @Override
    public void ossResult(ArrayList<OssImageResponse> response) {
        verifyDaren(response);
    }

    @Override
    public void ossVideoResult(ArrayList<OssVideoResponse> response) {

    }

}
